//
//  LineOnViewController.m
//  dmao-customer
//
//  Created by macbook on 2017/10/12.
//  Copyright © 2017年 秦慕乔. All rights reserved.
//

#import "LineOnViewController.h"
#import "LOClassViewController.h"
#import "LOHomeThreeTableViewCell.h"
#import "SDCycleScrollView.h"
#import "LOShopCarViewController.h"
#import "LOHomeBottomCollectionViewCell.h"
#import "LOSearchViewController.h"
#import "LOCommentViewController.h"
#import "LOStoreViewController.h"
#import "CreateQrcodeImage+Utils.h"
#import "LOGoodsDetailViewController.h"
#import "LOGoodsViewController.h"

@interface LineOnViewController ()<UITableViewDelegate,UITableViewDataSource,SDCycleScrollViewDelegate,UICollectionViewDataSource, UICollectionViewDelegate>
{
    NSMutableArray *_activityGoodsArr;
    NSMutableArray *_activityImgArr;
    NSMutableArray *_recomGoodsArr;
    NSMutableArray *_slideImgArr;
    NSMutableArray *_cellCountArr;
    NSMutableArray *_picArr;
    UITableView *_tab;
    UICollectionView *_bottomCollectionView;
    NSString *_cartNum;
    UIView *_BackgroundView;
    UIImageView *_QRCodeBack;
    UIImageView *_QRCode;
    UIImageView *_img2;
}
@property (weak, nonatomic) IBOutlet UIView *ClassView;
@property (strong, nonatomic) SDCycleScrollView *ADView;
@property (strong, nonatomic) UIView *headerView;
@property (strong, nonatomic) UIView *bottomView;
@end

@implementation LineOnViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    _activityGoodsArr = [NSMutableArray array];
    _activityImgArr = [NSMutableArray array];
    _recomGoodsArr = [NSMutableArray array];
    _slideImgArr = [NSMutableArray array];
    _cellCountArr = [NSMutableArray array];
    _picArr = [NSMutableArray array];
    
    [self downloadData];
    [self createBottomCollectionView];
}

-(void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBarHidden = YES;
}

- (void)createTopView
{
    _headerView = [[UIView alloc] init];
//    _headerView.backgroundColor = [UIColor redColor];
    if (_activityImgArr.count != 0) {
        _headerView.frame = CGRectMake(0, 0, WIDTH, WIDTH*326/414+(_activityImgArr.count*160)+79+182);
    }
    
    [self.view addSubview:_headerView];
    
}

- (void)createADView
{
    for (int i=0; i<_slideImgArr.count; i++) {
        [_picArr addObject:[Utils getImaSting:_slideImgArr[i][@"adFile"]]];
    }
    _ADView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, WIDTH, WIDTH*226/414) imageURLStringsGroup:_picArr];

    _ADView.pageControlStyle = SDCycleScrollViewPageContolStyleAnimated;
    _ADView.autoScrollTimeInterval = 3;
    _ADView.userInteractionEnabled = YES;
    _ADView.delegate = self;
    _ADView.dotColor = [UIColor whiteColor];
    //加载到视图上
    [_headerView addSubview:_ADView];
    
    //创建searchbar
    [_ADView addSubview:[Utils createSearchBar:10 and:10 and:WIDTH-50]];
    
    [_ADView addSubview:({
        UIButton *searchBtn = [UIButton buttonWithType:UIButtonTypeSystem];
        searchBtn.frame = CGRectMake(10, 10, WIDTH-55, 30);
        [searchBtn addTarget:self action:@selector(searchClick) forControlEvents:UIControlEventTouchUpInside];
        searchBtn;
    })];
    
    UIImageView *carImg = [[UIImageView alloc] initWithFrame:CGRectMake(WIDTH-35, 12, 22, 22)];
    [carImg setImage:[UIImage imageNamed:@"LOHomeShopCar"]];
    [_ADView addSubview:carImg];
    
    UILabel *shopCarNum = [[UILabel alloc] initWithFrame:CGRectMake(WIDTH-19, 5, 14, 14)];
    shopCarNum.backgroundColor = [UIColor redColor];
    shopCarNum.font = [UIFont systemFontOfSize:10.0f];
    shopCarNum.textColor = [UIColor whiteColor];
    shopCarNum.textAlignment = NSTextAlignmentCenter;
    [shopCarNum.layer setCornerRadius:7.0];
    shopCarNum.layer.masksToBounds=YES;
    if ([_cartNum isEqualToString:@"0"]) {
        shopCarNum.hidden = YES;
    }else{
        shopCarNum.hidden = NO;
        shopCarNum.text = _cartNum;
    }
    [_ADView addSubview:shopCarNum];
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
    btn.frame = CGRectMake(WIDTH-35, 8, 30, 30);
    [btn addTarget:self action:@selector(shopCarClick) forControlEvents:UIControlEventTouchUpInside];
    [_ADView addSubview:btn];
    
    if (IPHONE5S) {
        _ClassView.frame = CGRectMake(0, _ADView.bottom+2, WIDTH, WIDTH*80/414);
    }else if (IPHONE6){
        _ClassView.frame = CGRectMake(0, _ADView.bottom+10, WIDTH, WIDTH*80/414);
    }else{
        _ClassView.frame = CGRectMake(0, _ADView.bottom+15, WIDTH, WIDTH*80/414);
    }
    
    [_headerView addSubview:_ClassView];
    
    //热门活动
    if (_activityImgArr.count != 0) {
        UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, _ClassView.bottom+10, WIDTH, 8)];
        line.backgroundColor = [UIColor colorWithHex:0xf2f2f2];
        [_headerView addSubview:line];
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, line.bottom+10, 100, 20)];
        label.text = @"热门活动 >";
        label.textColor = RGB(86, 86, 86);
        label.font = [UIFont systemFontOfSize:16.0];
        [_headerView addSubview:label];
        
        UIView *bottomLin = [[UIView alloc] initWithFrame:CGRectMake(0, label.bottom+10, WIDTH, 1)];
        bottomLin.backgroundColor = [UIColor colorWithHex:0xf2f2f2];
        [_headerView addSubview:bottomLin];
        
        UIImageView *img = [[UIImageView alloc] initWithFrame:CGRectMake(3, bottomLin.bottom+10, WIDTH-6, 160)];
        [img sd_setImageWithURL:[NSURL URLWithString:[Utils getImaSting:_activityImgArr[0][@"adFile"]]]];
        [_headerView addSubview:img];
        
        _img2 = [[UIImageView alloc] initWithFrame:CGRectMake(3, img.bottom+10, WIDTH-6, 160)];
        [_img2 sd_setImageWithURL:[NSURL URLWithString:[Utils getImaSting:_activityImgArr[1][@"adFile"]]]];
        [_headerView addSubview:_img2];
    }
    
    if (_activityGoodsArr.count != 0) {
        [self creatFourView:_activityGoodsArr[0] andX:0 andY:_img2.bottom+10];
        [self creatFourView:_activityGoodsArr[1] andX:WIDTH/2 andY:_img2.bottom+10];
        [self creatFourView:_activityGoodsArr[2] andX:0 andY:_img2.bottom+100];
        [self creatFourView:_activityGoodsArr[3] andX:WIDTH/2 andY:_img2.bottom+100];
    }
}

- (void)creatFourView:(NSDictionary *)dic andX:(CGFloat )x andY:(CGFloat )y
{
    UIView *vi = [[UIView alloc]initWithFrame:CGRectMake(x, y, WIDTH/2, 90)];
    UILabel *name = [[UILabel alloc]initWithFrame:CGRectMake(10, 10, WIDTH/2-20, 20)];
    name.font = [UIFont systemFontOfSize:15.0f];
    name.textColor = [UIColor colorWithHex:0x333333];
    name.text = [dic objectForKey:@"goodsName"];
    [vi addSubview:name];
    
    UILabel *price = [[UILabel alloc]initWithFrame:CGRectMake(10, name.bottom+5, 100, 20)];
    price.textColor = [UIColor colorWithRed:139/255.0 green:139/255.0 blue:139/255.0 alpha:1.0];
    price.font = [UIFont systemFontOfSize:14.0f];
    price.text = [NSString stringWithFormat:@"￥%.2f", [[dic objectForKey:@"shopPrice"] floatValue]];
    [vi addSubview:price];
    
    UIImageView *ima = [[UIImageView alloc]initWithFrame:CGRectMake(WIDTH/2-10-70, 30, 70, vi.height-31)];
    [ima sd_setImageWithURL:[NSURL URLWithString:[Utils getImaSting:[dic objectForKey:@"goodsImg"]]]];
    [vi addSubview:ima];
    
    UIView *line = [[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH/2, 1)];
    line.backgroundColor = [UIColor colorWithHex:0xf2f2f2];
    [vi addSubview:line];
    
    UIView *line2 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 1, vi.height)];
    line2.backgroundColor = [UIColor colorWithHex:0xf2f2f2];
    [vi addSubview:line2];
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(0, 0, WIDTH/2, 90);
    [vi addSubview:btn];
    btn.tag = [[dic objectForKey:@"goodsId"] integerValue];
    [btn addTarget:self action:@selector(HotBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    [_headerView addSubview:vi];
}

- (void)HotBtnClick:(UIButton *)btn{
    LOGoodsDetailViewController *detail = [[LOGoodsDetailViewController alloc] init];
    detail.goodsId = [NSString stringWithFormat:@"%ld", btn.tag];
    detail.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:detail animated:YES];
}

- (void)searchClick
{
    LOSearchViewController *search = [[LOSearchViewController alloc] init];
    search.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:search animated:YES];
}

- (void)shopCarClick
{
    if ([Utils getUserToken]) {
        LOShopCarViewController *shopCar = [[LOShopCarViewController alloc] init];
        shopCar.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:shopCar animated:YES];
    }else{
        [self.view Message:@"请先登录"];
    }
}

- (IBAction)ClassClick:(UIButton *)sender {
    LOClassViewController *class = [[LOClassViewController alloc] init];
    class.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:class animated:YES];
}

- (IBAction)CodeClick:(UIButton *)sender {
    [THWManager PostHttp:API(MineEqcode) Parameters:@{@"userToken":[Utils getUserToken]} Success:^(id responseObject) {
        if ([String(responseObject[@"status_code"]) isEqualToString:@"1008"]) {
            [self.view Message:responseObject[@"msg"]];
        }else{
            if (_QRCodeBack) {
                _BackgroundView.hidden = NO;
                _QRCodeBack.hidden = NO;
            }else{
                _BackgroundView = [[UIView alloc] initWithFrame:CGRectMake(0, 20, WIDTH, HEIGHT-20)];
                _BackgroundView.backgroundColor = [UIColor grayColor];
                _BackgroundView.alpha = 0.6f;
                [self.view addSubview:_BackgroundView];
                
                _QRCodeBack = [[UIImageView alloc] initWithFrame:CGRectMake((WIDTH-(190*WIDTH/280))/2, (HEIGHT-(260*HEIGHT/475))/2, 190*WIDTH/280, 260*HEIGHT/475)];
                _QRCodeBack.userInteractionEnabled = YES;
                [_QRCodeBack setImage:[UIImage imageNamed:@"QRCodeBackground"]];
                [self.view addSubview:_QRCodeBack];
                
                _QRCode = [[UIImageView alloc] initWithFrame:CGRectMake(20, 20, 190*WIDTH/280-40, 190*WIDTH/280-40)];
                
                NSString *qrcodStr = [CreateQrcodeImage_Utils CreateQrcodeString:responseObject[@"data"][@"url"]];
                CIImage *CIImage = [CreateQrcodeImage_Utils createErweimaWithString:qrcodStr];
                _QRCode.image = [CreateQrcodeImage_Utils createNonInterpolatedUIImageFormCIImage:CIImage withSize:200.0f];
                [_QRCodeBack addSubview:_QRCode];
                
                UILabel *codeLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 260*HEIGHT/475-40, 190*WIDTH/280, 20)];
                codeLabel.text = [NSString stringWithFormat:@"ID:%@", responseObject[@"data"][@"id"]];
                codeLabel.textColor = [UIColor whiteColor];
                codeLabel.textAlignment = NSTextAlignmentCenter;
                [_QRCodeBack addSubview:codeLabel];
                
                UIButton *closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
                closeBtn.frame = CGRectMake(190*WIDTH/280-30, 0, 30, 30);
                [closeBtn setTitle:@"X" forState:UIControlStateNormal];
                [closeBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
                [closeBtn addTarget:self action:@selector(closeClick) forControlEvents:UIControlEventTouchUpInside];
                [_QRCodeBack addSubview:closeBtn];
            }
            
        }
    } andFalse:^(NSError *error) {
        
    }];
}

- (void)closeClick
{
    _BackgroundView.hidden = YES;
    _QRCodeBack.hidden = YES;
}

- (IBAction)ProfitClick:(UIButton *)sender {
    LOGoodsViewController *goods = [[LOGoodsViewController alloc] init];
    goods.hidesBottomBarWhenPushed = YES;
    goods.comeFrom = @"profit";
    [self.navigationController pushViewController:goods animated:YES];
}

- (IBAction)StoreClick:(UIButton *)sender {
    
    LOStoreViewController *store = [[LOStoreViewController alloc] init];
    store.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:store animated:YES];
}

- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index
{
    
}

- (void)createTableView
{
    _tab = [[UITableView alloc] initWithFrame:CGRectMake(0, 20, WIDTH, HEIGHT-20)];
    _tab.delegate = self;
    _tab.dataSource = self;
    [_tab registerNib:[UINib nibWithNibName:@"LOHomeThreeTableViewCell" bundle:nil] forCellReuseIdentifier:@"LOHomeThreeTableViewCell"];
    _tab.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tab.showsVerticalScrollIndicator = NO;
    _tab.tableHeaderView = _headerView;
    _bottomView.hidden = NO;
    _tab.tableFooterView = _bottomView;
    [self.view addSubview:_tab];
}

- (void)downloadData
{
    [self.view loadingOnAnyView];
    NSDictionary *dic = @{@"userToken":[Utils getUserToken]};
    [THWManager GetHttp:API(LineOnHome) Parameters:dic Success:^(id responseObject) {
        [self.view removeAnyView];
        
        NSDictionary *dic = [Utils getData:responseObject];
        if ([dic isEqual:@""]) {
            return;
        }
        _activityGoodsArr = [dic objectForKey:@"activityGoods"];
        _activityImgArr = [dic objectForKey:@"activityImg"];
        NSArray *arr = [dic objectForKey:@"goodsCats"];
        _cartNum = [NSString stringWithFormat:@"%@", dic[@"cartsNum"]];
        for (NSDictionary *dic in arr) {
            if ([dic[@"goods"] count] != 0) {
                [_cellCountArr addObject:dic];
            }
        }
        _recomGoodsArr = [dic objectForKey:@"recomGoods"];
        _slideImgArr = [dic objectForKey:@"slideImg"];
        [self createTopView];
        [self createTableView];
        [self createADView];
        [_tab reloadData];
        [_bottomCollectionView reloadData];
    } andFalse:^(NSError *error) {
        [self.view removeAnyView];
    }];
}

#pragma mark - UITableView
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _cellCountArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    LOHomeThreeTableViewCell*cell = [tableView dequeueReusableCellWithIdentifier:@"LOHomeThreeTableViewCell" forIndexPath:indexPath];
    if (!cell) {
        cell = [[LOHomeThreeTableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"LOHomeThreeTableViewCell"];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell showData:_cellCountArr[indexPath.row]];
    cell.btnclick = ^(NSInteger goodId){
        
        NSLog(@"%ld", goodId);
        LOGoodsDetailViewController *detail = [[LOGoodsDetailViewController alloc] init];
        detail.goodsId = [NSString stringWithFormat:@"%ld", goodId];
        detail.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:detail animated:YES];
    };
    [cell.TopBtn addTarget:self action:@selector(TopBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    return cell;
}

- (void)TopBtnClick:(UIButton *)btn{
    LOClassViewController *class = [[LOClassViewController alloc] init];
    class.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:class animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([[_cellCountArr[indexPath.row] objectForKey:@"goods"] count] == 6) {
        return 455;
    }else{
        return 415;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}

#pragma mark - UICollectionView
- (void)createBottomCollectionView
{
    _bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, WIDTH/2*230/160*2+63+20)];
    _bottomView.hidden = YES;
    [self.view addSubview:_bottomView];
    
    UIView *Topline = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 8)];
    Topline.backgroundColor = [UIColor colorWithHex:0xf2f2f2];
    [_bottomView addSubview:Topline];
    
    UILabel *Label = [[UILabel alloc] initWithFrame:CGRectMake(10, Topline.bottom+13, 80, 20)];
    Label.text = @"最新推荐>";
    Label.font = [UIFont systemFontOfSize:16.0];
    Label.textColor = RGB(86, 86, 86);
    [_bottomView addSubview:Label];
    
    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, Label.bottom+12, WIDTH, 1)];
    line.backgroundColor = [UIColor colorWithHex:0xf2f2f2];
    [_bottomView addSubview:line];
    
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    _bottomCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, line.bottom+10, WIDTH, WIDTH/2*230/160*2+20) collectionViewLayout:layout];
    _bottomCollectionView.backgroundColor = [UIColor whiteColor];
    _bottomCollectionView.delegate = self;
    _bottomCollectionView.dataSource = self;
    _bottomCollectionView.showsVerticalScrollIndicator = NO;
    _bottomCollectionView.scrollEnabled = NO;
    [_bottomCollectionView registerNib:[UINib nibWithNibName:@"LOHomeBottomCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"LOHomeBottomCollectionViewCell"];
    [_bottomView addSubview:_bottomCollectionView];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _recomGoodsArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    LOHomeBottomCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"LOHomeBottomCollectionViewCell" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor whiteColor];
    [cell showData:_recomGoodsArr[indexPath.row]];
    cell.layer.borderWidth = 1;
    cell.layer.borderColor = [RGB(232, 234, 234) CGColor];
    return cell;
    
}

// 设置cell的水平间距
- (CGFloat) collectionView:(UICollectionView *)collectionView
                    layout:(UICollectionViewLayout *)collectionViewLayout
minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 0;
}

// 设置cell的竖直间距
- (CGFloat) collectionView:(UICollectionView *)collectionView
                    layout:(UICollectionViewLayout *)collectionViewLayout
minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 10;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    float length = WIDTH/ 2;
    return CGSizeMake(length - 1, length*230/160);
}

//定义每个UICollectionView 的 margin(边缘，范围)
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    // 上左下右的空隙
    return UIEdgeInsetsMake(0, 0, 0, 0);
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"%@", _recomGoodsArr[indexPath.row][@"goodsId"]);
    LOGoodsDetailViewController *detail = [[LOGoodsDetailViewController alloc] init];
    detail.goodsId = _recomGoodsArr[indexPath.row][@"goodsId"];
    detail.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:detail animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */


@end
